let itemList = ["百度地图", "高德地图", "腾讯地图"];
	// "baidumap://map/direction?mode=driving&destination=上地&origin=西二旗&src=push&viaPoints={"viaPoints":[{"name":"北京西站","lat":39.902463,"lng":116.327737}]}";

// #ifdef APP-PLUS
var hasBaiduMap = plus.runtime.isApplicationExist({
	pname: 'com.baidu.BaiduMap',
	action: 'baidumap://'
});
var hasQQ = plus.runtime.isApplicationExist({
	pname: 'com.tencent.map',
	action: 'qqmap://'
});
var hasAmap;
let AppitemList = [];
if (plus.os.name == 'Android') {
	hasAmap = plus.runtime.isApplicationExist({
		pname: 'com.autonavi.minimap',
		action: 'androidamap://'
	});
} else {
	hasAmap = plus.runtime.isApplicationExist({
		pname: 'com.autonavi.minimap',
		action: 'iosamap://'
	});
}
if (hasBaiduMap) {
	AppitemList.push({
		title: "百度地图"
	})
}
if (hasAmap) {
	AppitemList.push({
		title: "高德地图"
	})
}
if (hasQQ) {
	AppitemList.push({
		title: "腾讯地图"
	})
}
// #endif
//规划路线
function openMapRoutePlan(options, mode) {
	var bdapp = "baidumap://map/direction";
	var bdappDown = "http://map.baidu.com/zt/qudao/newfengchao/1012337a/html/slide.html";
	var qqmap = "qqmap://map/routeplan";
	var qqmapDefault = "https://apis.map.qq.com/uri/v1/routeplan";
	var amapuri = "iosamap://route/plan/";
	var amapuriDown="https://apps.apple.com/cn/app/id461703208"
	// #ifdef APP-PLUS
	if (plus.os.name == 'Android') {
		amapuri = "amapuri://route/plan/";
		amapuriDown = "http://wap.amap.com/";
	}
	// #endif
	let startGeo={}
	let endGeo={
		latitude:options.destination.latitude,
		longitude: options.destination.longitude
	}
	let originName = options.origin && options.origin.name ? options.origin.name : "起点";
	let destinationName = options.destination.name ? options.destination.name : "终点";
	let viaPoints = options.viaPoints?options.viaPoints:{}
	
	var bdMode = "driving";
	if (mode == "bus") {
		bdMode = "transit";
	} else if (mode == "walk") {
		bdMode = "walking";
	} else if (mode == "bike") {
		bdMode = "riding";
	}
	bdapp += "?coord_type=gcj02&mode=" + bdMode + "&src=uniapp&viaPoints="+viaPoints;
	if (options.origin) {
		startGeo={
			latitude:options.origin.latitude,
			longitude:options.origin.longitude
		}
		bdapp += "&origin=name:" + originName + "|latlng:" + startGeo.latitude + "," + startGeo
			.longitude;
	}
	if (options.destination) {
		bdapp += "&destination=name:" + destinationName + "|latlng:" + endGeo.latitude +
			"," + endGeo.longitude
	}
	var amapMode = 0;
	if (mode == "bus") {
		amapMode = 1;
	} else if (mode == "walk") {
		amapMode = 2;
	} else if (mode == "bike") {
		amapMode = 3;
	}
	amapuri += "?sourceApplication=uniapp&t=" + amapMode+"&viaPoints="+viaPoints;
	if (options.origin) {
		amapuri += "&slat=" + startGeo.latitude + "&slon=" + startGeo
			.longitude + "&sname=" + originName;
	}
	if (options.destination) {
		amapuri +="&dlat=" + endGeo.latitude + "&dlon=" + endGeo.longitude +
			"&dname=" + destinationName;
	}
	qqmap += "?type=" + mode +"&viaPoints="+viaPoints;
	if (options.origin) {
		qqmap += "&from=" + originName + "&fromcoord=" + startGeo.latitude + "," +
			startGeo.longitude;
	}
	if (options.destination) {
		qqmap += "&to=" + destinationName + "&tocoord=" + endGeo.latitude + "," + endGeo
			.longitude;
	}
	qqmapDefault += "?type=" + mode + "&policy=1&viaPoints="+viaPoints;
	if (options.origin) {
		qqmapDefault += "&from=" + originName + "&fromcoord=" +
			startGeo.latitude + "," + startGeo.longitude ;
	}
	if (options.origin) {
		qqmapDefault += "&to=" + destinationName + "&tocoord=" + endGeo.latitude +
			"," + endGeo.longitude;
	}
	openActionSheet(bdapp,amapuri,qqmap,qqmapDefault)
}
//导航
function toNavigation(options) {
	let destinationName = options.destination.name ? options.destination.name : "终点";
	let viaPoints = options.viaPoints?options.viaPoints:{}
	let endGeo={
		latitude:options.destination.latitude,
		longitude:options.destination.longitude
	}
	var bdapp = "baidumap://map/navi?location=" + endGeo.latitude + "," + endGeo.longitude + "&query=" +
		destinationName + "&coord_type=gcj02&src=uniapp&viaPoints="+viaPoints;
	var bdappDown = "http://map.baidu.com/zt/qudao/newfengchao/1012337a/html/slide.html";
	var qqmap = "qqmap://map/routeplan?type=drive&to=" + destinationName + "&tocoord=" + endGeo.latitude + "," +
		endGeo.longitude;
	var qqmapDefault = "https://apis.map.qq.com/uri/v1/routeplan?type=drive&to=" + destinationName + "&tocoord=" +
		endGeo.latitude + "," + endGeo.longitude + "&policy=1";
	var amapuri="iosamap://navi?sourceApplication=uniapp&lat=" + endGeo.latitude + "&lon=" + endGeo
			.longitude + "&poiname=" + destinationName + "&dev=1";
	var amapuriDown = "https://apps.apple.com/cn/app/id461703208";
	// #ifdef APP-PLUS
	if (plus.os.name == 'Android') {
		amapuri = "androidamap://navi?sourceApplication=uniapp&lat=" + endGeo.latitude + "&lon=" + endGeo
			.longitude + "&poiname=" + destinationName + "&dev=1";
		amapuriDown = "http://wap.amap.com/";
	}
	// #endif
	openActionSheet(bdapp,amapuri,qqmap,qqmapDefault)
}
//唤起
function openActionSheet(bdapp,amapuri,qqmap,qqmapDefault){
	// #ifdef APP-PLUS
	plus.nativeUI.actionSheet({
			title: "选择导航",
			cancel: "取消",
			buttons: AppitemList
		},
		(res)=> {
			if(res.index==0){//取消
				return
			}
			if (hasBaiduMap && hasAmap) {
				if (res.index == 1) {
					appOpenUrl(bdapp);
					return
				}
				if (res.index == 2) {
					appOpenUrl(amapuri);
					return
				}
				 if (res.index == 3&&hasQQ) {
					appOpenUrl(qqmap);
					return
				}
				appOpenUrl(qqmapDefault);
				return
			}
			if (!hasBaiduMap && hasAmap) {
				if (res.index == 1) {
					appOpenUrl(amapuri);
					return
				}
				if (res.index == 2&&hasQQ) {
					appOpenUrl(qqmap);
					return
				} 
				appOpenUrl(qqmapDefault);
				return
			}
			 if (hasBaiduMap && !hasAmap) {
				if (res.index == 1) {
					appOpenUrl(bdapp);
					return
				}
				if (res.index == 2&& hasQQ) {
					appOpenUrl(qqmap);
					return
				}
				appOpenUrl(qqmapDefault);
				return
			}
			if (res.index == 1 && hasQQ) {
				appOpenUrl(qqmap);
				return
			}
			appOpenUrl(qqmapDefault);
		}
	);
	// #endif
	// #ifndef APP-PLUS
	uni.showActionSheet({
		itemList: itemList,
		success: (res) => {
			if (res.tapIndex == 0) {
				openURL(bdapp, bdappDown)
			} else if (res.tapIndex == 1) {
				openURL(amapuri, amapuriDown)
			} else {
				openURL(qqmap, qqmapDefault)
			}
	
		}
	})
	// #endif
}


function appOpenUrl(_url) {
	plus.runtime.openURL(encodeURI(_url));
}

function openURL(url, downLoadUrl) {
	window.location.href = encodeURI(url);
	var startTime = Date.now();
	var endTime = 0;
	var t = setTimeout(() => {
		endTime = Date.now() - startTime;
		if (endTime >= 2000 && !(document.hidden || document.webkitHidden)) {
			window.location.href = encodeURI(downLoadUrl);
		} else {
			clearTimeout(t)
		}
	}, 2000)

}
let PI = 3.14159265358979324;
let x_pi = 3.14159265358979324 * 3000.0 / 180.0

function delta(lat, lon) {
	var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
	var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
	var dLat = transformLat(lon - 105.0, lat - 35.0);
	var dLon = transformLon(lon - 105.0, lat - 35.0);
	var radLat = lat / 180.0 * PI;
	var magic = Math.sin(radLat);
	magic = 1 - ee * magic * magic;
	var sqrtMagic = Math.sqrt(magic);
	dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
	dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
	return {
		'lat': dLat,
		'lon': dLon
	};
}

function gcj_encrypt(wgsLat, wgsLon) {
	if (outOfChina(wgsLat, wgsLon))
		return {
			'lat': wgsLat,
			'lon': wgsLon
		};
	var d = delta(wgsLat, wgsLon);
	return {
		'lat': wgsLat + d.lat,
		'lon': wgsLon + d.lon
	};
}

function bd_decrypt(bdLat, bdLon) {
	var x = bdLon - 0.0065,
		y = bdLat - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
	var gcjLon = z * Math.cos(theta);
	var gcjLat = z * Math.sin(theta);
	return {
		'lat': gcjLat,
		'lon': gcjLon
	};
}

function outOfChina(lat, lon) {
	if (lon < 72.004 || lon > 137.8347)
		return true;
	if (lat < 0.8293 || lat > 55.8271)
		return true;
	return false;
}

function transformLat(x, y) {
	var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
	ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
	ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
	return ret;
}

function transformLon(x, y) {
	var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
	ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
	ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
	return ret;
}
//途径点坐标转换
function transformViaPoints(type,viaPoints){
	let obj = JSON.parse(viaPoints);
	let viaPointsArr = obj.viaPoints;
	for(let i=0;i<viaPointsArr.length; i++){
		if(type=='wgs84'){
			viaPointsArr[i].latitude = gcj_encrypt(viaPointsArr[i].latitude,viaPointsArr[i].longitude).lat
			viaPointsArr[i].longitude=gcj_encrypt(viaPointsArr[i].latitude, viaPointsArr[i].longitude).lon
		}else if(type=='bd09'){
			viaPointsArr[i].latitude=bd_decrypt(viaPointsArr[i].latitude, viaPointsArr[i].longitude).lat
			viaPointsArr[i].longitude=bd_decrypt(viaPointsArr[i].latitude, viaPointsArr[i].longitude).lon
		}
	}
	console.log(viaPointsArr)
	return JSON.stringify({viaPoints:viaPointsArr})
}
export default {
	 // 获取地址坐标
	addressCoordinates(cityName) {
		return new Promise(resolve => {
			plus.maps.Map.geocode(
				cityName,
				event => {
					var address = event.address; // 转换后的地理位置
					var point = event.coord; // 转换后的坐标信息
					var coordType = event.coordType; // 转换后的坐标系类型
					resolve({
						latitude: point.latitude,
						longitude: point.longitude,
						cityName: cityName,
						name: event.address,
						address: event.address,
					})
				},
				e => {
					var address = e.address; // 转换后的地理位置
					var point = e.coord; // 转换后的坐标信息
					var coordType = e.coordType; // 转换后的坐标系类型
					resolve({
						latitude: point.latitude,
						longitude: point.longitude,
						name: e.address,
						address: e.address,
					})
				}
			);
		})
	},
	/* 路程规划 */
	routePlan(options, type = "gcj02") {
		let _mode = options.mode ? options.mode : "drive";
		if (type.toLowerCase() == "wgs84") {
			if (options.origin) {
				options.origin.latitude = gcj_encrypt(options.origin.latitude, options.origin.longitude).lat
				options.origin.longitude = gcj_encrypt(options.origin.latitude, options.origin.longitude).lon
			}
			options.destination.latitude = gcj_encrypt(options.destination.latitude, options.destination.longitude).lat
			options.destination.longitude = gcj_encrypt(options.destination.latitude, options.destination.longitude).lon
			options.viaPoints = transformViaPoints("wgs84",options.viaPoints)
		} else if (type.toLowerCase() == "bd09") {
			if (options.origin) {
				options.origin.latitude = bd_decrypt(options.origin.latitude, options.origin.longitude).lat
				options.origin.longitude = bd_decrypt(options.origin.latitude, options.origin.longitude).lon
			}
			options.destination.latitude = bd_decrypt(options.destination.latitude, options.destination.longitude).lat
			options.destination.longitude = bd_decrypt(options.destination.latitude, options.destination.longitude).lon
			options.viaPoints = transformViaPoints("bd09",options.viaPoints)
		}
		// #ifdef MP
		// #ifdef MP-WEIXIN
		const mapCtx = wx.createMapContext(options.mapId, this);
		mapCtx.openMapApp({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			destination: options.destination.name,
			complete: res => {
				console.log(res);
			}
		});
		// #endif
		// #ifdef MP-QQ
		qq.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif
		// #ifdef MP-ALIPAY
		my.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif
		// #ifdef MP-360 || MP-BAIDU || MP-TOUTIAO
		uni.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif

		// #endif
		// #ifndef MP
		switch (uni.getSystemInfoSync().platform) {
			case 'android':
				console.log('运行Android上')
				openMapRoutePlan(options, _mode)
				break;
			case 'ios':
				console.log('运行iOS上')
				openMapRoutePlan(options, _mode)
				break;
			default:
				console.log('运行在开发者工具上')
				break;
		}

		// #endif
	},
	navigation(options, type = "gcj02") {
		if (type.toLowerCase() == "wgs84") {
			options.destination.latitude = gcj_encrypt(options.destination.latitude, options.destination.longitude).lat
			options.destination.longitude = gcj_encrypt(options.destination.latitude, options.destination.longitude).lon
		} else if (type.toLowerCase() == "bd09") {
			options.destination.latitude = bd_decrypt(options.destination.latitude, options.destination.longitude).lat
			options.destination.longitude = bd_decrypt(options.destination.latitude, options.destination.longitude).lon
		}
		// #ifdef MP
		// #ifdef MP-WEIXIN
		const mapCtx = wx.createMapContext(options.mapId, this);
		mapCtx.openMapApp({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			destination: options.destination.name,
			complete: res => {
				console.log(res);
			}
		});
		// #endif
		// #ifdef MP-QQ
		qq.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif
		// #ifdef MP-ALIPAY
		my.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif
		// #ifdef MP-360 || MP-BAIDU || MP-TOUTIAO
		uni.openLocation({
			latitude: options.destination.latitude,
			longitude: options.destination.longitude,
			name: options.destination.name
		})
		// #endif
		// #endif
		// #ifndef MP
		switch (uni.getSystemInfoSync().platform) {
			case 'android':
				console.log('运行Android上')
				toNavigation(options)
				break;
			case 'ios':
				console.log('运行iOS上')
				toNavigation(options)
				break;
			default:
				console.log('运行在开发者工具上')
				break;
		}
		// #endif
	}
}

